import { DeviceEventEmitter} from 'react-native';
import { plus33H, LightMode, transfer2DeviceValue, transfer2RawValue, Recv_Error_Def, Loop_4Way_Extreme_Value } from "./SerialCommon";
import { controller4wayConstant, response4wayType, SerialController4Way} from "./SerialController4Way";
import XLog from './XLog';


export default class SerialController4Client{
    constructor(address, index, id){
        this.address = address;
        this.index = index;
        this.id = id;
        this.function = {};
        this.lightMode = LightMode.POSITIVE_MODE;
        this.lightExtreme = Loop_4Way_Extreme_Value;
        this.currentRecvstr = "";

        this.addFunction("getLightMode", this.getLightMode.bind(this));
        this.addFunction("setLightMode", this.setLightMode.bind(this));
        this.addFunction("readAddress", this.readAddress.bind(this));
        this.addFunction("setLampLight", this.setLight.bind(this));
        this.addFunction("readLight", this.readLight.bind(this));
    }

    addFunction(event, callback){
        this.function[event] = callback;
    }

    getLightMode(){
        return this.lightMode;
    }

    updateLightMode(value){
        if(value == LightMode.POSITIVE_MODE.value){
            this.lightMode = LightMode.POSITIVE_MODE;
        }else if(value == LightMode.NEGATIVE_MODE.value){
            this.lightMode = LightMode.NEGATIVE_MODE;
        }
    }

    setLightMode(value){
        if(this.lightMode.value == value){
            return;
        }
        this.updateLightMode(value);
        //this.writeVersion(this.lightMode.value);
        DeviceEventEmitter.emit("lightMode");
    }

    checkRecvByte(inputMsg){
        this.currentRecvstr = this.currentRecvstr + inputMsg;
        return SerialController4Way.checkRecvLen(this.currentRecvstr);
    }

    matchAddress(inputMsg, address){
        if(address == null || address.length == 0){
            return false;
        }
        let response_address = SerialController4Way.fetchResponseAddress(inputMsg);
        let fixedAddress = (Array(4).join(0) + address).slice(-12);
        // let fixedAddress = (Array(4).join(0) + address).slice(-4);
        return response_address.toUpperCase() == fixedAddress.toUpperCase();
    }

    handleReceiveMessage(inputMsg){
        
        let message = "";
        let checkRecvRet = this.checkRecvByte(inputMsg);
        if(checkRecvRet > 0){
            message = this.currentRecvstr.substr(0, checkRecvRet);
            this.currentRecvstr = this.currentRecvstr.length > checkRecvRet ? this.currentRecvstr.substr(checkRecvRet, this.currentRecvstr.length - checkRecvRet) : "";
        } else {
            if(checkRecvRet == Recv_Error_Def.ERR_START_FLAG || checkRecvRet == Recv_Error_Def.ERR_CHECKSUM){
                this.currentRecvstr = "";
            }
            return { error: checkRecvRet};
        }
        if(!this.matchAddress(message, this.address)){
            return {error: Recv_Error_Def.ERR_ADDRESS_DISMATCH};
        }

        XLog.d("SerialController4Client handleReceiveMessage," + " message:" + JSON.stringify(message));
        var type = SerialController4Way.getMessageType(message);
        switch(type){
            case response4wayType.broadcast:
                this.address = SerialController4Way.parserQueryDeviceAddressResponse(message);
                return { type: "message", event: "readAddress", message: this.address, index: this.index, id: this.id};

            case response4wayType.setlampstate:
                var result = SerialController4Way.parserSetLampState(message);
                return { type: "message", event: "setLampState", message: result, index: this.index, id: this.id};

            case response4wayType.setlamplight:
                var result = SerialController4Way.parserSetLampLight(message);
                return { type: "message", event: "setLampLight", message: result, index: this.index, id: this.id};

            case response4wayType.readlight:
                var result = SerialController4Way.parserQueryDeviceInfo(message, this.index);
                result = transfer2RawValue(this.lightMode.value, result, this.lightExtreme);
                return { type: "message", event: "readLight", message: result, index: this.index, id: this.id};
            
            default:
                return {};
        }
    }

    readAddress(){
        return SerialController4Way.generateRequest(controller4wayConstant.broadcastAddress, controller4wayConstant.control_broadcast_req, 0, "");
    }

    setLight(light){
        if(light == null){
            return;
        }        
                
        light = transfer2DeviceValue(this.lightMode.value, light, this.lightExtreme);
        var data = SerialController4Way.formatSetLampLight(light);
        var request = SerialController4Way.generateRequest(this.address, controller4wayConstant.control_setlamplight_req, data.length/2, data);
        return request;
    }

    // 查询灯状态
    readLight(){
        // var data = plus33H("0000601301");
        var data = plus33H("00006009");
        return SerialController4Way.generateRequest(this.address, controller4wayConstant.control_querydeviceinfo_req, data.length/2, data);
    }

    sendRequest(message){
        if(message && message.event){
            if ( this.address == null ){
                return this.readAddress();
                XLog.e("loop controller address null");
                return "";
            }
            if (this.function[message.event]){
                return this.function[message.event](message.data);
            }
        }
    }
} 